/*
 * @Author: Zhang Yingying
 * @Date: 2020-11-05 10:40:36
 * @LastEditors: Zhang Yingying
 * @LastEditTime: 2020-11-16 17:20:26
 */
import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/pageTitle'
import { routesWhiteList } from './config/settings'

NProgress.configure({
  easing: 'ease',
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
})
router.beforeResolve(async (to, from, next) => {
  NProgress.start()
  let hasToken = store.getters['user/token']
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      next()
      const userId = store.getters['user/userId']
      if (userId) {
        next()
      } else {
        try {
          await store.dispatch('user/getInfo')
          var accessRoutes = await store.dispatch('routes/setRoutes')
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (exp) {
          console.log(exp)
          await store.dispatch('user/resetToken')
          NProgress.done()
        }
      }
    }
  } else {
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
  document.title = getPageTitle(to.meta.title)
})
router.afterEach(() => {
  NProgress.done()
})
